<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-06-26 13:53
 * Modified Time: 2019-06-26 13:53
 * Version: 2.0
 */

namespace App\Modules\Member\Repositoryies;


use App\Models\Schedule;
use App\Modules\Member\Criterias\getScheduleCriteria;
use Flower\Core\Repository\Eloquent\BaseRepository;
use function GuzzleHttp\Psr7\str;
use Illuminate\Support\Facades\DB;

class ScheduleRepository extends BaseRepository
{

	public function model()
	{
		// TODO: Implement model() method.
		return Schedule::class;
	}

	/**
	 * 查询排班时间列表 某天或者某时间段
	 * @param $storeId
	 * @param $startDay
	 * @param $endDay
	 * @param null $barberId
	 * @param null $status
	 * @return mixed
	 */
	public function getScheduleList($storeId, $startDay, $endDay, $barberId = null, $status = null)
	{
		return $this->getByCriteria(new getScheduleCriteria($storeId, $startDay, $endDay, $barberId, $status));
	}


	/**
	 * 获取日期列表
	 * @param $data
	 * @return array
	 */
	public function getDate($start_time, $end_time)
	{
		$timestamp1 = strtotime($start_time);
		$timestamp2 = strtotime($end_time);
		$days = ($timestamp2 - $timestamp1) / 86400 + 1;
		$date = [];
		for ($i = 0; $i < $days; $i++) {
			$date[] = date('Y-m-d', $timestamp1 + (86400 * $i));
		}
		return $date;
	}

	/**
	 * 获取详细的周日程安排
	 * @param $list
	 * @param $dates
	 * @param $isDefault
	 * @param $appointList
	 * @return array
	 */
	public function scheduleList($list, $dates, $isDefault, $appointList, $isApp = false)
	{
		$newList = [];
		$weekArray = array("Su", "Mo", "Tu", "We", "Th", "Fr", "Sa");
		$today = strtotime(date('Y-m-d', time()));
		//获取当前时间
		foreach ($dates as $v) {
			if ($isApp) {
				if (strtotime($v) < time()) {
					$newList[] = [
						'date'   => $v,
						'status' => 3
					];
				} else {
					if (in_array($v, $appointList)) {
						$newList[] = [
							'date'   => $v,
							'status' => 2
						];
					} else {
						if (empty($list)) {
							$newList[] = [
								'date'   => $v,
								'status' => ($isDefault && (strtotime($v) > time())) ? 1 : 0,
							];
						} else {

							$newList[] = isset($list[$v]) ? [
								'date'   => $list[$v]['plan_date'],
								'status' => $list[$v]['status']
							] : [
								'date'   => $v,
								'status' => ($isDefault && (strtotime($v) > time())) ? 1 : 0
							];
							// foreach ($list as $value){
							// 	if($v == $value['plan_date']){
							// 		$newList[]=[
							// 			'date' => $value['plan_date'],
							// 			'status' => $value['status']
							// 		];
							// 	}else{
							// 		$newList[]=[
							// 			'date' => $v,
							// 			'status' => ($isDefault && (strtotime($v) > time())) ? 1 : 0,
							// 		];
							// 	}
							// }
						}
					}
				}
			} else {
				if (strtotime($v) < $today) {
					$newList[] = [
						'date'   => $v,
						'week'   => $weekArray[date('w', strtotime($v))],
						'status' => 3
					];
				} else {
					if (in_array($v, $appointList)) {
						$newList[] = [
							'date'   => $v,
							'week'   => $weekArray[date('w', strtotime($v))],
							'status' => 2
						];
					} else {
						if (empty($list)) {
							$newList[] = [
								'date'   => $v,
								'week'   => $weekArray[date('w', strtotime($v))],
								'status' => ($isDefault && (strtotime($v) >= $today)) ? 1 : 0,
							];
						} else {
							$newList[] = isset($list[$v]) ? [
								'date'   => $list[$v]['plan_date'],
								'week'   => $weekArray[date('w', strtotime($v))],
								'status' => $list[$v]['status']
							] : [
								'date'   => $v,
								'week'   => $weekArray[date('w', strtotime($v))],
								'status' => ($isDefault && (strtotime($v) >= $today)) ? 1 : 0
							];
						}
					}
				}
			}

		}
		return $newList;
	}


	/**
	 * 批量新增
	 * @param $data
	 * @return mixed
	 */
	public function createAll($data)
	{
		return $this->model->insert($data);
	}

	public function deleteByDate($barberId, $storeId, $date)
	{
		$days = date("t", strtotime($date));
		$startDate = strtotime($date . '-01');
		$endDate = strtotime($date . '-' . $days);
		$res = $this->model->where(['user_id' => $barberId, 'store_id' => $storeId])->where('plan_date', ">=", $startDate)->where('plan_date', "<=", $endDate)->delete();
		return $res;
	}


	/**
	 * 判断该用户今日是否上班
	 * @param $userId
	 * @param $storeId
	 * @param null $date
	 * @return mixed
	 */
	public function isWorked($userId, $storeId, $date = null)
	{
		$where = [
			'user_id'   => $userId,
			'store_id'  => $storeId,
			'plan_date' => empty($date) ? strtotime(date('Y-m-d', time())) : $date
		];
		return $this->findWhere($where)->first();
	}

	/**
	 * 排班任务
	 * @return bool
	 */
	public function rewriteAll()
	{
		$currentMonth = date('Y-m', time());
		$nextMonth = date("Y-m", strtotime("+1 month"));
		$sql = 'select a.user_id,a.store_id,a.status,a.plan_date  from `hx_schedule` as a 
left join(select user_id,store_id,FROM_UNIXTIME(`plan_date`, "%Y-%m") as dates from `hx_schedule` where FROM_UNIXTIME(`plan_date`, "%Y-%m")="' . $nextMonth . '" group by `user_id`,`store_id`) as b 
 on a.`user_id`=b.`user_id` and a.`store_id` = b.`store_id`  where FROM_UNIXTIME(a.`plan_date`, "%Y-%m")="' . $currentMonth . '" and b.user_id is null';
		$list = DB::select($sql);
		if (!empty($list)) {
			foreach ($list as $v) {
				if (isset($v->plan_date)) {
					$v->plan_date = $this->getNewDate($v->plan_date);
					$newData = json_decode(json_encode($v), true);
					$this->create($newData);
				}
			}
		}
		return true;
	}


	public function getNewDate($planDate)
	{
		$year = date('Y', $planDate);
		$month = date('m', $planDate);
		$day = date('d', $planDate);
		if ($month != '12' && $month != '01') {
			$month = $month + 1;
			$planDate = strtotime($year . '-' . $month . '-' . $day);
		} else if ($month == '12') {
			$year = $year + 1;
			$month = '01';
			$planDate = strtotime($year . '-' . $month . '-' . $day);
		} else if ($month == '01') {
			$days = date('t', strtotime($year . '-02'));
			if ($days >= $day) {
				$planDate = strtotime($year . '-' . $month . '-' . $day);
			} else {
				$planDate = false;
			}
		}
		return $planDate;
	}
}